package com.leyou.auth.service.impl;

import com.leyou.auth.service.UserAutnService;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.dto.Payload;
import com.leyou.dto.UserDetails;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.UserDTO;
import com.leyou.utils.JwtUtils;
import feign.FeignException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.leyou.constants.JwtConstants.*;

/**
 * @author 付
 */
@Service
public class UserAutnServiceImpl implements UserAutnService {
    @Autowired
    private UserClient userClient;
    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response) {
        //解析cookie中的jwt
        String jwt = CookieUtils.getCookieValue(request, COOKIE_NAME);
        if (jwt==null){
            //用户未登录
            return;
        }
        try {
            //解析jwt
            Payload payload = jwtUtils.parseJwt(jwt);
            //删除redis
            Long userid = payload.getUserDetail().getId();
            jwtUtils.deleteJwt(userid);

        } catch (Exception e) {
           //解析jwt失败，放弃退出
        }
        //删除cookie
        CookieUtils.deleteCookie(COOKIE_NAME,DOMAIN,response);

    }

    @Override
    public void login(String username, String password, HttpServletResponse response) {
        //根据用户名和密码查询用户

        try {
            UserDTO  userDTO = userClient.querynameandpwd(username, password);

        //对查询结果进行判断
        if (userDTO==null){
            throw new LyException(401,"用户名或者密码错误");
        }

        //生成jwt
      String jwt=  jwtUtils.createJwt(UserDetails.of(userDTO.getId(),userDTO.getUsername()));
        //写入cookie
        writeJwt2Cookie(response,jwt);
        } catch (FeignException e) {
            if (e.status()==400){
                //用户名或者密码错误
                throw new LyException(e.status(),e.contentUTF8());
            }
            throw new LyException(500,"验证用户失败");
        }
    }
    private void writeJwt2Cookie(HttpServletResponse response,String jwt){
        Cookie cookie = new Cookie(COOKIE_NAME, jwt);
        cookie.setPath(COOKIE_PATH);
        cookie.setHttpOnly(true);
        cookie.setDomain(DOMAIN);
        response.addCookie(cookie);
    }
}
